﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using log4net;

namespace Jiubang.Wap.HttpModules {
    /// <summary>
    /// 关闭不在白名单内的开放频道访问
    /// </summary>
    public sealed class FriendlyWidFilterModule : IHttpModule {
        private static readonly ILog _log = LogManager.GetLogger(typeof (FriendlyWidFilterModule));
        private static readonly List<int> _unFilterWids = new List<int>(10);
        private static readonly string _url;

        static FriendlyWidFilterModule() {
            try {
                var wids = ConfigurationManager.AppSettings["UnFilterWids"];
                if (!string.IsNullOrEmpty(wids)) {
                    var items = wids.Split(',');
                    foreach (var s in items) {
                        int wid;
                        if (int.TryParse(s.Trim(), out wid)) _unFilterWids.Add(wid);
                    }
                    _unFilterWids.Sort();
                }
                _url = ConfigurationManager.AppSettings["RedirectUrl"];
                if (string.IsNullOrEmpty(_url)) {
                    _url = "http://3g.cn/index.aspx";
                }
            } catch (Exception exception) {
                _log.Fatal(exception);
                throw;
            }
        }

        #region IHttpModule Members

        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context) {
            context.BeginRequest += ContextBeginRequest;
        }

        /// <summary>
        /// 空操作
        /// </summary>
        public void Dispose() {}

        #endregion

        private static void ContextBeginRequest(object sender, EventArgs e) {
            var context = ((HttpApplication) sender).Context;
            if (context == null )
                return;

            int wid;

            if (int.TryParse(context.Request.QueryString.Get("wid"), out wid) && wid != 0 && _unFilterWids.BinarySearch(wid) < 0)
                //开放频道且不在白名单内的跳转
                context.Response.Redirect(_url, true);
        }
    }
}